function authInterceptor(API, auth) {
	return {
		// automatically attach Authorization header
		request: function(config) {
			var token = auth.getToken();
			if (token) {
				config.headers.Authorization = 'Bearer ' + token;
			}
			return config;
		},

		// If a token was sent back, save it
		response: function(res) {
			if (res.config.url.indexOf(API) === 0 && res.data.data && res.data.data.token) {
				auth.saveToken(res.data.data.token);
			}
			return res;
		},
	}
}

function authService($window) {
	var self = this;

	// Add JWT methods here
	self.parseJwt = function(token) {
		var base64Url = token.split('.')[1];
		var base64 = base64Url.replace('-', '+').replace('_', '/');
		return JSON.parse($window.atob(base64));
	};
	self.saveToken = function(token) {
		$window.localStorage['jwtToken'] = token;
	};
	self.getToken = function() {
		return $window.localStorage['jwtToken'];
	};
	self.logout = function() {
	  $window.localStorage.removeItem('jwtToken');
	};
	self.isAuthed = function() {
		var token = self.getToken();
		if (token) {
			var params = self.parseJwt(token);
			return Math.round(new Date().getTime() / 1000) <= params.exp;
		} else {
			return false;
		}
	};
}

function userService($http, API, auth) {
	var self = this;
	self.testToken = function() {
		return $http.get('http://121.40.121.237:9001/token/test')
	};

	// add authentication methods here
	self.register = function(mobile, captcha) {
		console.log({
			mobile: mobile,
			captcha: captcha
		});
		return $http.post(API + '/signup', {
			mobile: mobile,
			captcha: captcha
		});
	};
	self.login = function(mobile, captcha) {
		return $http.post(API + '/login', {
			mobile: mobile,
			captcha: captcha
		});
	};
	self.captcha = function(mobile) {
		return $http.get(API + '/captcha?mobile=' + mobile);
	};
	self.logout = function() {
		return $http.get(API + '/logout').then(function(res) {
			auth.logout();
			return res;
		});
	};
}

function MainCtrl(user, auth, $interval, $scope) {
	var self = this;
	self.captchaBtn = '获取验证码';
	self.captchaBtnDisabled = false;
	var counter;

	function handleRequest(res) {
		self.message = '';
		var data = res.data;
		console.log(data.data);
		self.message = data.msg;
		if (data.code == 400) {
			return auth.logout();
		}
		if (data.code != 0) {
			self.message = '错误：' + data.msg;
		}
	};

	self.getCaptcha = function() {
		if ($scope.userForm.mobile.$invalid) {
			self.message = '手机号码必须输入';
			return;
		}
		self.captchaBtnDisabled = true;
		var count = 60;
		self.captchaBtn = count + '秒后重新获取';
		counter = $interval(function() {
			self.captchaBtn = --count + '秒后重新获取';
			if (count < 1) {
				self.captchaBtn = '获取验证码';
				self.captchaBtnDisabled = false;
				if (angular.isDefined(counter)) {
					$interval.cancel(counter);
					counter = undefined;
				}
			}
		}, 1000);
		user.captcha(self.mobile).then(handleRequest, handleRequest);
	};

	self.login = function() {
		if ($scope.userForm.mobile.$invalid) {
			self.message = '手机号码必须输入';
			return;
		}
		if (!self.captcha) {
			self.message = '验证码必须输入';
			return;
		}
		user.login(self.mobile, self.captcha)
			.then(handleRequest, handleRequest)
	};
	self.register = function() {
		user.register(self.mobile, self.captcha)
			.then(handleRequest, handleRequest)
	};
	self.testToken = function() {
		user.testToken()
			.then(handleRequest, handleRequest)
	};
	self.logout = function() {
		self.mobile = '';
		self.captcha = '';
		user.logout()
			.then(handleRequest, handleRequest);
	};
	self.isAuthed = function() {
		return auth.isAuthed ? auth.isAuthed() : false
	};
}

var app = angular.module('app', []);
app.factory('authInterceptor', authInterceptor)
	.service('user', userService)
	.service('auth', authService)
	.constant('API', 'http://121.40.121.237:4400/api')
	.config(function($httpProvider) {
		$httpProvider.interceptors.push('authInterceptor');
	})
	.controller('MainCtrl', MainCtrl);